<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Doctrine\DBAL\Types\Type;

class Assuntos extends SiteController {

    public function index() {
        $this->assign('assuntos', $this->getAssuntos());
        $this->display('assuntos/index');
    }

    public function getAssuntos() {
        $findBy = array('ativo' => true);
        return $this->doctrine->em->getRepository('MenusPrincipais')->findBy(
                        $findBy, array('ordem' => 'ASC'), null, null);
    }

    public function pesquisa(){
        $assunto = $this->input->post('assunto');
        $this->assign('resultado', $this->pesquisar($assunto));
        $this->display('assuntos/pesquisa');
    }
    
    /////////////////////////
    
    private function pesquisar($titulo){
        $principais = $this->getMenusPrincipaisByTitulo($titulo);
        $menusPrincipais = array();
        $arrayNotIn = array();
        if (!empty($principais)){
            foreach ($principais as $principal){
                array_push($arrayNotIn, $principal->get_id_menu_principal());
                $menusPrincipais[$principal->get_id_menu_principal()] = $principal;
            }
        }
        $menus = $this->getMenusByTitulo($titulo, $arrayNotIn);
        
        if(!empty($menus)){
            foreach($menus as $menu){
                $menuPrincipal = $menu->get_menu_principal();
                if (!isset($menusPrincipais[$menuPrincipal->get_id_menu_principal()])){
                    $menuPrincipal->set_menus(new Doctrine\Common\Collections\ArrayCollection());
                    $menuPrincipal->get_menus()->add($menu);
                    $menusPrincipais[$menuPrincipal->get_id_menu_principal()] = $menuPrincipal;
                } else {
                    $menusPrincipais[$menuPrincipal->get_id_menu_principal()]->get_menus()->add($menu);
                }
                
            }
        }
        return $menusPrincipais;
    }
    
    private function getMenusPrincipaisByTitulo($title){
        $sql = "select t from MenusPrincipais t where lower(t.titulo) like :title and t.ativo = true";
        $query = $this->doctrine->em->createQuery($sql);
        $query->setParameter('title', '%'.strtolower($title).'%', Type::STRING );
        return $query->getResult();
    }
    
    private function getMenusByTitulo($title, $menusPrincipaisNotIn){
        $sql = "select t from Menus t where lower(t.titulo) like :title and t.ativo = true and t.menu_principal not in (:menus_principais)";
        $query = $this->doctrine->em->createQuery($sql);
        $query->setParameter('title', '%'.strtolower($title).'%', Type::STRING );
        $query->setParameter('menus_principais', count($menusPrincipaisNotIn) > 0 ? $menusPrincipaisNotIn : 0);
        return $query->getResult();
    }
}

/* End of file home.php */
/* Location: ./application/controllers/admin/home.php */